package com.ipgeocoder.util;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import com.maxmind.geoip.regionName;

/**
 * <a href="IPGeocoderUtil.java.html"><b><i>View Source</i></b></a>
 *
 * @author Brian Wing Shun Chan
 *
 */
public class IPGeocoderUtil {

	public static List getIPInfo(String ipAddress) {
		return _instance._getIPInfo(ipAddress);
	}

	private IPGeocoderUtil() {
		_init();
	}

	private void _init() {
		try {
			
			
			if (_lookupService == null) {
				File file = new File("GeoLiteCity.dat");
				
				
				_lookupService = new LookupService(file.getAbsoluteFile(),LookupService.GEOIP_MEMORY_CACHE);
			}
		}
		catch (IOException ioe) {
			_log.error(ioe.getMessage());
		}
	}

	 private List<Object> _getIPInfo(String ipAddress) {
        _init();
        
        if (_lookupService != null) {
                List<Object> list = new ArrayList<Object>();
                Location location = _lookupService.getLocation(ipAddress);
                 list.add((Location)location);
                 list.add(regionName.regionNameByCode(location.countryCode, location.region));                        
        
                return list;
        }
        else {
                return null;
        }
}


	private static Log _log = LogFactoryUtil.getLog(IPGeocoderUtil.class);

	private static IPGeocoderUtil _instance = new IPGeocoderUtil();

	private LookupService _lookupService;

}